<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


use GatewayWorker\Lib\Gateway;
use app\http\Http;

use think\Db;

use think\facade\Env;
use think\facade\Log;
use think\facade\Request;

/**
 * 返回JSON参数
 * @param array|string $msg 返回信息
 * @param bool $data 返回数据
 * @param int $code
 * @return false|string
 */
function successJson($msg, $data = false, $code = 0)
{
    $req_data = "";
    $user = Request::param("_user");
    if (isset($user["user_type"]) && $user["user_type"] = "user") {
        \app\sys\model\UserActionLog::write(1, $msg, "", $req_data);
    } else {
        \app\sys\model\StaffActionLog::write(1, $msg, "", $req_data);
    }
    $arr = [
        'code' => $code,
        'msg' => $msg,
    ];
    if ($data !== false) $arr['data'] = $data;
    return think\response\Json::create($arr, 'json', 200, [], [JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE]);
}

/**
 * 返回JSON参数
 * @param array|string $msg 返回信息
 * @param int $code
 * @param string $remark
 * @param bool $data 返回数据
 * @return false|string
 */
function failedJson($msg, $code = 1, $remark = "", $data = false)
{
    $user = Request::param("_user");

    if (isset($user["user_type"]) && $user["user_type"] = "user") {
        \app\sys\model\UserActionLog::write(0, $msg, $remark);
    } else {
        \app\sys\model\StaffActionLog::write(0, $msg, $remark);
    }
    $arr = [
        'code' => $code,
        'msg' => $msg,
    ];
    if ($data !== false) $arr['data'] = $data;
    return think\response\Json::create($arr, 'json', 200, [], [JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE]);
}


/**
 * 返回JSON参数
 * @param array|string $msg 返回信息
 * @param bool $data 返回数据
 * @param int $code
 * @return false|string
 */
function pxsSuccessJson($msg, $data = false, $code = 0)
{
    $req_data = "";
    \app\sys\model\UserActionLog::write(1, $msg, "", $req_data);
    $arr = [
        'code' => $code,
        'msg' => $msg,
    ];
    if ($data !== false) $arr['data'] = $data;
    return think\response\Json::create($arr, 'json', 200, [], [JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE]);
}

/**
 * 返回JSON参数
 * @param array|string $msg 返回信息
 * @param int $code
 * @param string $remark
 * @param bool $data 返回数据
 * @return false|string
 */
function pxsFailedJson($msg, $code = 1, $remark = "", $data = false)
{
    \app\sys\model\UserActionLog::write(0, $msg, $remark);
    $arr = [
        'code' => $code,
        'msg' => $msg,
    ];
    if ($data !== false) $arr['data'] = $data;
    return think\response\Json::create($arr, 'json', 200, [], [JSON_FORCE_OBJECT, JSON_UNESCAPED_UNICODE]);
}


// ws 数据
/**
 * @param $msg
 * @param $data
 * @param int $code
 * @return false|string
 */
function wsJson($msg, $data, $code = 0)
{
    return json_encode($data);
}

// 列表数据输出
/**
 * @param $date
 * @param $count
 * @return array
 */
function listDate($date, $count): array
{
    $arr = [
        "list" => $date,
        "count" => $count,
    ];
    return $arr;
}

// 列表数据输出
/**
 * @param $date
 * @param $count
 * @return array
 */
function listTJDate($aa, $date, $count): array
{
    $arr = [
        "all" => $aa,
        "list" => $date,
        "count" => $count,
    ];
    return $arr;
}

//获取毫秒
/**
 * @return float
 */
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

//判断登录设备是pc还是app
/**
 * @return string
 */
function get_device_type(): string
{
    $agent = Request::header("user-agent");
    if (stripos($agent, "ios") !== false || stripos($agent, "android") !== false) {
        return "app";
    } else if (stripos($agent, "MicroMessenger") != false) {

        return "wx";
    } else {
        return "pc";
    }
}

/**
 * @param string $string 需要加密的字符串
 * @param string $key 密钥
 * @return string
 */
function encrypt($string, $key)
{

    // openssl_encrypt 加密不同Mcrypt，对秘钥长度要求，超出16加密结果不变
    $data = openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);

    $data = strtolower(bin2hex($data));

    return $data;
}


/**
 * @param string $string 需要解密的字符串
 * @param string $key 密钥
 * @return string
 */
function decrypt($string, $key)
{
    if (!$string) return "";
    $decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);

    return $decrypted;
}

/**
 * @return string
 */
function uuid()
{
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr($chars, 0, 8) . '-'
        . substr($chars, 8, 4) . '-'
        . substr($chars, 12, 4) . '-'
        . substr($chars, 16, 4) . '-'
        . substr($chars, 20, 12);
    return $uuid;
}

/**
 * @param $dutyId
 * @return string
 * 判断售前售后
 */
function serverType($dutyId)
{
    // 售前
    $SERVER = Env::get("STAFF.SERVER_BE_DUTY");
    $dutyIdArrBe = explode(",", $SERVER);
    $SERVER2 = Env::get("STAFF.SERVER_BE_DUTY_MAN");
    $dutyIdArrBeM = explode(",", $SERVER2);
    if (in_array($dutyId, array_merge($dutyIdArrBe, $dutyIdArrBeM))) return "be";
    // 后
    $SERVER = Env::get("STAFF.SERVER_AF_DUTY");
    $dutyIdArrAf = explode(",", $SERVER);
    $SERVER2 = Env::get("STAFF.SERVER_AF_DUTY_MAN");
    $dutyIdArrAfM = explode(",", $SERVER2);
    if (in_array($dutyId, array_merge($dutyIdArrAf, $dutyIdArrAfM))) return "af";
    // 其他
    return "ot";

}

/**
 * @param $type
 * @return array|false|string[]
 * 获取售前售后职位数据
 */
//function getServerData($type)
//{
//    if($type == "be"){
//        $SERVER = Env::get("STAFF.SERVER_BE_DUTY");
//        $dutyIdArrBe = explode(",",$SERVER);
//        return $dutyIdArrBe;
//    }
//
//    if($type == "af"){
//        $SERVER = Env::get("STAFF.SERVER_AF_DUTY");
//        $dutyIdArrAf = explode(",",$SERVER);
//        return $dutyIdArrAf;
//    }
//    return [];
//}

/**
 * @param $list
 * @param $f
 * @param $pid
 * @return array
 */
function getMenu($list, $f, $pid)
{
    foreach ($list as $k => $v) {
        if ($v[$f] == $pid) {
            $data[$v['id']] = $v;
            $data[$v['id']]['children'] = getMenu($list, $f, $v['id']);
        }
    }

    $data1 = [];
    if (isset($data)) {
        ksort($data);
        foreach ($data as $k => $v) {
            $data1[] = $v;
        }
    }


    return isset($data1) ? $data1 : [];
}

//获取客户端ip
function get_request_ip()
{
    global $rq_ip;
    if (getenv("HTTP_CLIENT_IP")) {
        $rq_ip = getenv("HTTP_CLIENT_IP");
    } else if (getenv("HTTP_X_FORWARDED_FOR")) {
        $rq_ip = getenv("HTTP_X_FORWARDED_FOR");
    } else if (getenv("REMOTE_ADDR")) {
        $rq_ip = getenv("REMOTE_ADDR");
    } else {
        $rq_ip = "Unknow";
    }
}

//获取客户端请求时间
function get_request_time()
{
    global $rq_tm;
    if (isset($_SERVER['REQUEST_TIME'])) {
        $rq_tm = $_SERVER['REQUEST_TIME'];
    } else {
        $rq_tm = time();
    }
}

//获取客户端的来源于关键词
function get_request_su_kd()
{
    global $rq_su, $rq_kd, $rq_basesu, $rq_basekd;
    $rq_su = $rq_kd = $rq_basekd = 0;
    $rq_basesu = isset($_GET['su']) ? $_GET['su'] : 0;
    if (isset($_GET['su']) && $parseA = parse_url($_GET['su'])) {
        $rq_su = $parseA['host'];
        if ($parseA['query']) {
            parse_str($parseA['query'], $output);
            if ('www.baidu.com' == $rq_su) {
                if (isset($output['wd']) && isset($output['ie'])) {
                    if ($output['ie'] != 'utf-8') {
                        $rq_kd = urldecode(iconv($output['ie'], 'utf-8', $output['wd']));
                    } else {
                        $rq_kd = urldecode($output['wd']);
                    }
                }
            } elseif ('www.sogou.com' == $rq_su) {
                if (isset($output['query']) && isset($output['ie'])) {
                    if ($output['ie'] != 'utf8') {
                        $rq_kd = urldecode(iconv($output['ie'], 'utf-8', $output['query']));
                    } else {
                        $rq_kd = urldecode($output['query']);
                    }
                }
            } elseif ('www.so.com' == $rq_su) {
                if (isset($output['q']) && isset($output['ie'])) {
                    if ($output['ie'] != 'utf-8') {
                        $rq_kd = urldecode(iconv($output['ie'], 'utf-8', $output['q']));
                    } else {
                        $rq_kd = urldecode($output['q']);
                    }
                }
            } elseif (preg_match('/m\d{1,2}\.baidu\.com/', $rq_su)) {
                if (isset($output['word'])) {
                    $rq_kd = urldecode($output['word']);
                }
            }
            if (!$rq_kd) {
                $rq_kd = 0;
                $rq_basekd = 0;
            } else {
                $rq_basekd = $rq_kd;
                $rq_kd = base64_encode($rq_kd);
            }
        }
    }
}

//获取客户端请求的url地址分级
function get_request_u()
{
    global $rq_u, $rq_u1, $rq_u2, $rq_u3, $rq_u4, $rq_baseu;
    $rq_u = $rq_u1 = $rq_u2 = $rq_u3 = $rq_u4 = 0;
    $rq_baseu = isset($_GET['u']) ? $_GET['u'] : 0;
    if (isset($_GET['u']) && $_GET['u']) {
        $rq_u = $_GET['u'];
        $u = str_replace(array('http://', 'https://'), '', $_GET['u']);
        if ($pos = strpos($u, '?')) {
            $u = substr($u, 0, $pos);
        }
        $u = rtrim($u, '/');
        $a = explode('/', $u, 4);
        isset($a[0]) ? $rq_u1 = $a[0] : false;
        isset($a[1]) ? $rq_u2 = "{$rq_u1}/{$a[1]}" : false;
        isset($a[2]) ? $rq_u3 = "{$rq_u2}/{$a[2]}" : false;
        isset($a[3]) ? $rq_u4 = "{$rq_u3}/{$a[3]}" : false;
        $num = "rq_u" . count($a);
        $rq_u = $$num;
    }
}

//获取其他一般参数
function get_other_params()
{
    global $rq_cc, $rq_ck, $rq_cl, $rq_ds, $rq_fl, $rq_ja, $rq_ln, $rq_si, $rq_tt, $rq_cf, $rq_uid, $rq_pt, $rq_ocu, $rq_ua, $rq_uuid;
    isset($_GET['cc']) ? $rq_cc = intval($_GET['cc']) : $rq_cc = 0;
    isset($_GET['ck']) ? $rq_ck = intval($_GET['ck']) : $rq_ck = 0;
    isset($_GET['cl']) && strlen($_GET['cl']) < 10 ? $rq_cl = $_GET['cl'] : $rq_cl = 0;
    isset($_GET['ds']) && strlen($_GET['ds']) < 10 ? $rq_ds = $_GET['ds'] : $rq_ds = 0;
    isset($_GET['fl']) ? $rq_fl = intval($_GET['fl']) : $rq_fl = 0;
    isset($_GET['ja']) ? $rq_ja = intval($_GET['ja']) : $rq_ja = 0;
    isset($_GET['ln']) && strlen($_GET['ln']) < 10 ? $rq_ln = $_GET['ln'] : $rq_ln = 0;
    isset($_GET['si']) ? $rq_si = $_GET['si'] : $rq_si = 0;
    isset($_GET['tt']) ? $rq_tt = $_GET['tt'] : $rq_tt = 0;
    isset($_GET['cf']) ? $rq_cf = intval($_GET['cf']) : $rq_cf = 0;
    isset($_GET['uid']) ? $rq_uid = intval($_GET['uid']) : $rq_uid = 0;
    isset($_GET['pt']) && strlen($_GET['pt']) < 10 ? $rq_pt = $_GET['pt'] : $rq_pt = 0;
    isset($_GET['ocu']) && strlen($_GET['ocu']) < 40 ? $rq_ocu = $_GET['ocu'] : $rq_ocu = 0;
    isset($_GET['ua']) && strlen($_GET['ua']) < 40 ? $rq_ua = $_GET['ua'] : $rq_ua = 0;
    isset($_COOKIE['YPTJUUID']) ? $rq_uuid = $_COOKIE['YPTJUUID'] : $rq_uuid = 0;
}


function visited()
{
    $now_time = time();

    $referer_url = $_SERVER['HTTP_REFERER'];    //来自的页面地址

    $from_spider = $keywords = '';

    if (!empty($referer_url)) {
        if (strstr($referer_url, 'www.baidu.com')) {
            $referer_url = explode("&", $referer_url);

            foreach ($referer_url as $val) {
                if (strstr($val, 'wd=')) {
                    $keywords = explode("wd=", $val);

                    $keywords = $keywords[1];

                }

            }

            $from_spider = '百度';

            $keywords = urldecode($keywords);

        } elseif (strstr($referer_url, 'www.google')) {
            $referer_url = explode("&", $referer_url);

            foreach ($referer_url as $val) {
                if (strstr($val, 'q=')) {
                    $keywords = explode("q=", $val);

                    $keywords = $keywords[1];

                }

            }

            $from_spider = '谷歌';

            $keywords = urldecode($keywords);

        }

    }

//只判断了百度和谷歌的，其他的原理一样

    $theData = array(

        'access_time' => $now_time,

        'access_date' => date("Y-m-d", $now_time),

        'access_url' => $_SERVER['REQUEST_URI'],

        'referer_url' => $_SERVER['HTTP_REFERER'],

        'keywords' => $keywords,

        'ip_address' => $_SERVER['REMOTE_ADDR'],

        'from_spider' => $from_spider,

    );

    return $theData;
}

function timeDiff($begin_time, $end_time)

{
    if ($begin_time < $end_time) {
        $starttime = $begin_time;

        $endtime = $end_time;

    } else {
        $starttime = $end_time;

        $endtime = $begin_time;

    }

//计算天数

    $timediff = $endtime - $starttime;

    $days = intval($timediff / 86400);

//计算小时数

    $remain = $timediff % 86400;

    $hours = intval($remain / 3600);

//计算分钟数

    $remain = $remain % 3600;

    $mins = intval($remain / 60);

//计算秒数

    $secs = $remain % 60;

    $res = array("day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs);

    return $res;

}


function getDateFromRange($startdate, $enddate)
{

    $stimestamp = strtotime($startdate);
    $etimestamp = strtotime($enddate);

    // 计算日期段内有多少天
    $days = ($etimestamp - $stimestamp) / 86400 + 1;

    // 保存每天日期
    $date = array();

    for ($i = 0; $i < $days; $i++) {
        $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
    }

    return $date;
}


function mobiles($mobile)
{
    $pattern = "/^1[0-9]{10}$/";
    if ($mobile && !preg_match($pattern, $mobile)) {
        return "电话格式错误~";
    }
}

// 访问来源
function visitSource($beUrl, $url)
{

//    $beArr = [
//        "puxiansheng" => "直接访问",
//        "so.com" => "360搜索",
//        "baidu.com/link" => "百度自然搜索",
//        "sogou" => "搜狗",
//        "sm.cn"=> "神马搜索"
//    ];
//
//    $AfArr = [
//        "transfer_details-id" => "直接访问",
//        "transfer_list-qy"=> "百度自然搜索" ,
//        "#sogo"=>"搜狗",
//        "bd_vid" => "百度推广",
//        "360PCdg7596" =>"360搜索",
//        "#shenma"=> "神马搜索"
//    ];

    // 百度
    $headBD = [
        "baidu" => [
            "#" => "百度推广",
            "bd_vid" => "百度推广",
            "" => "百度自然搜索"
        ]
    ];

    // 搜狗
    $headSG = [
        "sogo" => [
            "#" => "搜狗推广",
            "" => "搜狗搜索"
        ]
    ];

    // 神马
    $headSM = [
        "shenma" => [
            "#" => "神马推广",
            "" => "神马搜索"
        ]
    ];

    // 360
    $head360 = [
        "so" => [
            "#" => "360推广",
            "" => "360搜索"
        ]
    ];

    // 自己搜索
    $self = [
        "" => "直接访问",
    ];

    $arr = [$headBD, $headSG, $headSM, $self, $head360];
    foreach ($arr as $k => $v) {
        foreach ($v as $k1 => $v1) {
            if (!empty($k1) && strpos($beUrl, $k1) > 0) {
                foreach ($v1 as $k2 => $v2) {
                    if (!empty($k2) && strpos($url, $k2) > 0) {
                        return [$v2, $url];
                    } else {
                        return [$v1[""], $url];
                    }
                }
            } elseif (empty($k1)) {
                return [$v1, $url];
            }
        }
    }

//    $beArr = [
//        "puxiansheng" => "直接访问",
//        "so.com" => "360搜索",
//        "baidu" => "百度自然搜索",
//        "sogou" => "搜狗",
//        "sm.cn"=> "神马搜索"
//    ];
//
//    $AfArr = [
//        "transfer_details-id" => "直接访问",
//        "transfer_list-qy"=> "百度自然搜索" ,
//        "#PCbd"=>"百度推广",
//        "#WAPbd"=>"百度推广",
//        "bd_vid" => "百度推广",
//        "#sogo"=>"搜狗",
//        "#360" =>"360推广",
//        "360PCdg7596" =>"360搜索",
//        "#shenma"=> "神马搜索",
//        "ada.baidu.com" => "百度其他"
//    ];
//
//
//    foreach ($beArr as $k => $v){
//        if (strpos($beUrl,$k) > 0) return [$v,$beUrl];
//    }
//
//    foreach ($AfArr as $k => $v){
//        if (strpos($url,$k) > 0) return [$v,$url];
//    }

    return ["非搜索引擎来源", $beUrl];
}

function getVisitSource($key = '')
{
    $arr = ["baiduTG" => "百度推广", "baiduSS" => "百度自然搜索", "sgTG" => "搜狗推广", "sgSS" => "搜狗搜索", "smTg" => "神马推广", "smSS" => "神马搜索",
        "360TG" => "360推广", "360SS" => "360搜索", "zj" => "直接访问", "ly" => "非搜索引擎来源"];
    if ($key) {
        return !isset($arr[$key]) ? "" : $arr[$key];
    }

    return $arr;
}

// 转数组
function object2array(&$object)
{
    $object = json_decode(json_encode($object), true);
    return $object;
}

// 获取来源url
function getComeUrl(): string
{
    return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
}

// 获取来源url
function getPcMobUrl($url): string
{
    $s = get_device_type();
    if ($url) return $url;
    if ($s == "pc") {
        //来自的页面地址
        return getComeUrl();
    } else {
        return getSite();
    }
}

// 获取当前url域名
function getSite(): string
{
    return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : "";
}

// 防止恶意调用
function OutSpiteCall(): string
{
    $ws1 = Env::get("SPITECALLOK.WS1");
    $ws2 = Env::get("SPITECALLOK.WS2");
    $ws3 = Env::get("SPITECALLOK.WS3");
    $ws4 = Env::get("SPITECALLOK.WS4");

    $ws = [$ws1, $ws2, $ws3, $ws4];
    $url = Request::header("Origin", "");
    \think\facade\Log::info("OutSpiteCall:{$url}");
    $search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';
    $url = trim($url);
    preg_match_all($search, $url, $rr);
    $d = json_encode($rr);
    \think\facade\Log::info("OutSpiteCall:{$d}");
    if (!$rr) {
        return "不能请求";
    }
    if (in_array($rr[4][0], $ws)) {
        return "不能请求";
    }
    return '';
}

//
function permiss()
{

}

// 名称转换
function getStaffName($staffName): string
{
    return "客服小" . mb_substr($staffName, 0, 1);
}

// 时间转化
function GetStrToTime($date_time = []): array
{
    if (empty($date_time)) return [];
    if (count($date_time) > 1 && empty($date_time[0]) || empty($date_time[1])) return [];
    return [strtotime($date_time[0] . " 00:00:00"), strtotime($date_time[1] . " 23:59:59")];
}

function GetDayBy($date_time = []): string
{
    if (empty($date_time)) return "";
    $strS = "";
    foreach ($date_time as $k => $v) {
        $s = explode("-", $v);
        $strS .= $s[2] . ",";
    }
    return $strS;
}

function GetStrByArr($arr = []): string
{
    if (empty($arr)) return "";
    $strS = "";
    $s = implode(",", $arr);
    $strS = mb_substr($s, 0, 81);
    return $strS;
}

function GetMonBy($date_time = []): string
{
    if (empty($date_time)) return "";
    $strS = "";
    foreach ($date_time as $k => $v) {
        $s = explode("-", $v);
        $strS = $s[0] . "-" . $s[1] . "-00";
    }
    return strtotime($strS);
}

// 异步处理
function syFunc($f)
{
    $pid = pcntl_fork();
    switch ($pid) {
        case -1:
            Log::info("Could not fork!");
            exit;
        case 0:
            $f();
            exit;
        default:
            Log::info("In parent!");
    }
}


function GetGwUrlInfo($sUrl): array

{
    $url = Env::get("GW.STOREURL");
    $resJ = Http::curlGet($url . "?url=" . $sUrl);
    $res = json_decode($resJ, true);
    if ($res["code"] != 200) {
        return ["false", $res["msg"] . "或数据不存在~"];
    }
    $res["data"]["result"]["url"] = $sUrl;

    return ["true",$res["data"]["result"]];

}


function getDateSql($tableName, $dateArr = [])
{


    $sql = sprintf(/** @lang text */ "CREATE TABLE %s (
            id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            data_time INT(11) NOT NULL DEFAULT '0'
            )", $tableName);
    Db::query($sql);
    $strSql = "";
    // 添加数据
    if ($dateArr) {
        $str = "";
        $daArr = getDateFromRange($dateArr[0], $dateArr[1]);
        foreach ($daArr as $k => $v) {
            $vTime = strtotime($v);
            $str .= "($vTime),";

        }
        $strSql = substr($str, 0, strlen($str) - 1);
    }

    // 添加数据
    if ($strSql) {
        $dataSql = sprintf(/** @lang text */ "INSERT INTO %s (data_time)
                                VALUES %s", $tableName, $strSql);
        Db::query($dataSql);
    }
}

function delDateSql($tableName)
{
    $delSql = sprintf(/** @lang text */ "DROP TABLE %s", $tableName);

    Db::query($delSql);

}

function isField($f)
{

    if (empty($f)) {
        return 1;
    }

    return $f;
}

function isNUllNumber($v): string
{
    if (empty($v)) {
        return 0;
    }
    return $v;

}
function isPhone($phonenumber):bool
{
    if (preg_match("/1[3456789]{1}\d{9}$/", $phonenumber)) {
        return true;
    } else {
        return false;
    }
}
